import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../../repositories/auth_repository.dart';
import '../../../translations/app_translations.dart';
import '../../../services/user_service.dart';
import '../../../services/token_service.dart';

class AuthController extends GetxController {
  // 表单控制器
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  
  // 密码可见性
  final RxBool isPasswordVisible = false.obs;
  
  // 登录状态
  final RxBool isLoading = false.obs;
  
  // 记住我状态
  final RxBool rememberMe = false.obs;
  
  // 表单校验Key
  final formKey = GlobalKey<FormState>();
  
  // 仓库服务
  final AuthRepository _authRepository = Get.find<AuthRepository>();
  
  // 令牌服务
  final TokenService _tokenService = Get.find<TokenService>();
  
  // 错误信息
  final RxString errorMessage = ''.obs;

  @override
  void onInit() {
    super.onInit();
    // 加载记住我的状态
    rememberMe.value = _tokenService.getRememberMe();
    
    // 如果有保存的凭证，自动填充
    if (rememberMe.value) {
      final credentials = _tokenService.getSavedCredentials();
      if (credentials != null) {
        usernameController.text = credentials['username'] ?? '';
        passwordController.text = credentials['password'] ?? '';
      }
    }
  }

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }
  
  // 切换密码可见性
  void togglePasswordVisibility() {
    isPasswordVisible.value = !isPasswordVisible.value;
  }
  
  // 切换记住我状态
  void toggleRememberMe() {
    rememberMe.value = !rememberMe.value;
    _tokenService.saveRememberMe(rememberMe.value);
  }
  
  // 表单验证
  String? validateUsername(String? value) {
    if (value == null || value.isEmpty) {
      return LocaleKeys.enterUsername.tr;
    }
    return null;
  }
  
  String? validatePassword(String? value) {
    if (value == null || value.isEmpty) {
      return LocaleKeys.enterPassword.tr;
    }
    if (value.length < 6) {
      return LocaleKeys.passwordLength.tr;
    }
    return null;
  }
  
  // 登录
  Future<void> login() async {
    if (!formKey.currentState!.validate()) {
      return;
    }
    
    isLoading.value = true;
    errorMessage.value = '';
    
    try {
      EasyLoading.show(status: LocaleKeys.loggingIn.tr);
      
      final username = usernameController.text.trim();
      final password = passwordController.text;
      
      await _authRepository.login(username, password);
      
      // 如果记住我，保存凭证
      _tokenService.saveRememberMe(rememberMe.value);
      if (rememberMe.value) {
        _tokenService.saveCredentials(username, password);
      }
      
      // 登录成功后获取用户信息
      try {
        await Get.find<UserService>().getUserInfo();
      } catch (e) {
        // 获取用户信息失败时只打印错误，不影响登录流程
        debugPrint('获取用户信息失败: $e');
      }
      
      EasyLoading.dismiss();
      Get.offAllNamed('/home'); // 登录成功后跳转到首页
    } catch (e) {
      EasyLoading.dismiss();
      errorMessage.value = e.toString().contains('error:')
          ? e.toString().split('error:')[1].trim()
          : LocaleKeys.checkCredentials.tr;
      Get.snackbar(
        LocaleKeys.loginFailed.tr,
        errorMessage.value,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      isLoading.value = false;
    }
  }
  
  // 退出登录
  Future<void> logout() async {
    try {
      EasyLoading.show(status: LocaleKeys.loggingOut.tr);
      await _authRepository.logout();
      // 清除用户信息，但保留记住我状态和凭证
      Get.find<UserService>().clearUserInfo();
      EasyLoading.dismiss();
      Get.offAllNamed('/login');
    } catch (e) {
      EasyLoading.dismiss();
      Get.snackbar(
        LocaleKeys.logoutFailed.tr,
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
} 